package algorithmExample;

/**
 * @author: zhang.rongqing
 * @since: 2019/10/31
 * //
 */
//反转字符串，遇到空格反转
//例子:are you ok? ==> ok？ you are
//要求需要用字符判断
public class ReverseCharArray {
    public String reverseArray(String str) {
        char[] result = new char[str.length()];
        //offset 记录需要反转的字符个数
        int offset = 0;
        for (int start = 0; start < str.length(); start++) {
            if (str.charAt(start) == ' ') {
                result[str.length() - 1 - start] = str.charAt(start);
                //减去空格位置
                addArray(str.toCharArray(), result, start - offset, offset);
                offset = 0;
            } else {
                offset++;
            }
        }
        //最后一次反转
        if (offset != 0) {
            addArray(str.toCharArray(), result, str.length() - offset, offset);
        }
        return result.toString();
    }

    private void addArray(char[] fromArray, char[] toArray, int start, int offset) {
//        if(start != 0){
//            toArray[fromArray.length-start] = fromArray[start];
//        }
        for (int i = 0; i < offset; i++) {
            toArray[fromArray.length - offset - start + i] = fromArray[start + i];
        }
    }

    public static void main(String[] args) {
        String input = "are you ok?";
        ReverseCharArray reverseCharArray = new ReverseCharArray();
        System.out.println(reverseCharArray.reverseArray(input));
    }
}
